﻿using ClientAppraise.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using Microsoft.VisualBasic;
using Wpf.Ui.Controls;

namespace ClientAppraise.Services.Impl
{
    public class ZxTitleRightService : IZxTitleRightService
    {
        private readonly List<KeyValuePair<int, ContentPresenter>> contents = new();

        public ContentPresenter EjectContentPresenter(int HashCode)
        {
            var value = contents.FirstOrDefault(t => t.Key == HashCode);

            if (!value.Equals(default(KeyValuePair<int, ContentPresenter>)))
            {
                contents.Remove(value);
            }

            var myReturn = value.Equals(default(KeyValuePair<int, ContentPresenter>)) ? value.Value : null;

            return myReturn?? throw new InvalidOperationException();
        }
        public void PushContentPresenter(int HashCode, ContentPresenter? contentPresenter)
        {
            if (contentPresenter == null) return;

            var value = contents.FirstOrDefault(t => t.Key == HashCode);

            if (value.Equals(default(KeyValuePair<int, ContentPresenter>)))
            {
                contents.Add(new KeyValuePair<int, ContentPresenter>(HashCode, contentPresenter));
            }
        }

        public ContentPresenter? GetContentPresenter(int HashCode)
        {
            var value = contents.FirstOrDefault(t => t.Key == HashCode);

            if (value.Equals(default(KeyValuePair<int, ContentPresenter>)))
            {
                if (contents.Count > 0)
                {
                    return contents[^1].Value;
                }
            }

            var myReturn = value.Equals(default(KeyValuePair<int, ContentPresenter>)) ? null : value.Value;

            return myReturn;
        }
        public ContentPresenter? GetContentPresenter()
        {
            var code = 0;
            foreach (Window window in Application.Current.Windows)
            {
                if (window.IsActive)//使用窗体类进行匹配查找
                {
                    code = window.GetHashCode();
                    break;
                }
            }

            return GetContentPresenter(code);
        }


        public void Show(UIElement? ele)
        {
            if (!Application.Current.Dispatcher.CheckAccess())
            {
                Application.Current.Dispatcher.Invoke(() => Show(ele));
                return;
            }

            ContentPresenter? cp = GetContentPresenter();

            if (cp == null) return;

            if (ele == null)
            {
                cp.Content = null;
                return;
            }

            (VisualTreeHelper.GetParent(ele) as Panel)?.Children.Remove(ele);
            cp.Content = ele;

        }
        public void Show()
        {
            Show(null);
        }
    }
}
